package com.yh.service.impl;

import com.yh.NotFoundException;
import com.yh.dao.BlogReposiory;
import com.yh.po.Blog;
import com.yh.po.Type;
import com.yh.service.BlogService;
import com.yh.util.MarkdownUtils;
import com.yh.util.MyBeanUtils;
import com.yh.vo.BlogQuery;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.*;

@Service
public class BlogServiceImpl implements BlogService {

    @Autowired
    private BlogReposiory blogReposiory;

    @Override
    public Blog getBlog(Long id) {
        Optional<Blog> blog = blogReposiory.findById(id);
        return blog.get();
    }

    @Transactional
    @Override
    public Blog getAndConvert(Long id) {
        Optional<Blog> blog = blogReposiory.findById(id);
        if(blog.get() == null){
            throw new NotFoundException("该博客不存在");
        }
        Blog b = new Blog();
        BeanUtils.copyProperties(blog.get(),b);
        String content = b.getContent();
        b.setContent(MarkdownUtils.markdownToHtmlExtensions(content));
        blogReposiory.updateViews(b.getId());
        return b;
    }

    @Override
    public Page<Blog> listBlog(Pageable pageable, BlogQuery blog) {
        return blogReposiory.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
                List<Predicate> predicates = new ArrayList<>();
                if (!"".equals(blog.getTitle()) && blog.getTitle() != null){
                    predicates.add(cb.like(root.<String>get("title"),"%"+blog.getTitle()+"%"));
                }
                if(blog.getTypeId() != null){
                    predicates.add(cb.equal(root.<Type>get("type").get("id"),blog.getTypeId()));
                }
                if(blog.isRecommend()){
                    predicates.add(cb.equal(root.<Boolean>get("recommend"),blog.isRecommend()));
                }
                cq.where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        },pageable);
    }

    @Override
    public Page<Blog> listBlog(Pageable pageable) {
        return blogReposiory.findAll(pageable);
    }

    @Override
    public Page<Blog> listBlog(String query, Pageable pageable) {
        return blogReposiory.findByQuery(query,pageable);
    }

    @Override
    public Page<Blog> listBlog(Long id, Pageable pageable) {
        return blogReposiory.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Join join = root.join("tags");
                return criteriaBuilder.equal(join.get("id"),id);
            }
        },pageable);
    }

    @Override
    public List<Blog> listRecommendBlogTop(Integer size) {

        Sort sort = Sort.by(Sort.Direction.DESC,"updateTime");
        Pageable pageable = PageRequest.of(0, size, sort);
        return blogReposiory.findTop(pageable);
    }

    @Override
    public List<Blog> listUpdateTimeBlog() {

        Sort s = Sort.by(Sort.Direction.DESC, "updateTime");
        Pageable pageable = PageRequest.of(0, 10000, s);
//        blogReposiory.findAll();
        return blogReposiory.findAll(s);
    }

//    @Override
//    public Map<String, List<Blog>> archivesBlog() {
//        List<String> years = blogReposiory.findGroupYear();
//        Map<String,List<Blog>> map = new HashMap<>();
//        for (String year : years) {
//            map.put(year,blogReposiory.findByYear(year));
//        }
//        return map;
//    }
//
//    @Override
//    public Long countBlog() {
//        return blogReposiory.count();
//    }

    @Transactional
    @Override
    public Blog saveBlog(Blog blog) {
        Long id = blog.getId();
        if(id == 0){
            blog.setCreateTime(new Date());
            blog.setUpdateTime(new Date());
            blog.setViews(0);
        }else {
            blog.setUpdateTime(new Date());
        }

        return blogReposiory.save(blog);
    }

    @Transactional
    @Override
    public Blog updateBlog(Long id, Blog blog) {

        Optional<Blog> byId = blogReposiory.findById(id);
        if(byId.get() == null){
            throw new NotFoundException("该博客不存在");
        }
        BeanUtils.copyProperties(blog,byId.get(), MyBeanUtils.getNullPropertyNames(blog));

        return blogReposiory.save(byId.get());
    }

    @Override
    public void deleteBlog(Long id) {
        blogReposiory.deleteById(id);
    }

    @Override
    public long CountBlog() {
        long count = blogReposiory.count();
        return count;
    }

    @Override
    public long CountViews() {
        return blogReposiory.countViews();
    }
}
